<template>
  <div class="infinite-container" style="padding-bottom: 45px;">
    <div class="greenTop">
      <div class="select-role flex flex_between">
        <div class="roleLeft flex flex_vcenter">
          <i class="w-icon w-icon-icon_common_jzr2 v-middle inline-block"></i>
          <span class="ml10 f16">就诊人</span>
        </div>
        <div class="roleRight flex flex_vcenter">
          <span class="mr10">{{familyPerson.realname}}</span>
          <!-- <span class="centerT">{{familyPerson.sexcode | getSex}}</span> -->
          <!-- <span>{{familyPerson.birthdate | getAge}}岁</span> -->
          <!-- <i class="iconfont icon-small-arrow-right t9" /> -->
        </div>
      </div>
    </div>
    <swipe style="height: calc(100% - 50px);overflow-y: scroll;" :auto="0" :showIndicators="false" :continuous="false" ref="swipe" @change="swipeChange">
      <swipe-item v-for="item in list" :key="item.prescriptionId" style="overflow-y: scroll;">
        <div>
          <ul class="topList">
            <li class="flex flex_between flex_vcenter">
              <span class="label">
                药品名称
                <i class="point"></i>
              </span>
              <input
                class="maxlen"
                type="text"
                maxlength="20"
                name="drugName"
                placeholder="输入药品名称"
                v-model="item.drugName"
              />
            </li>
            <li class="flex flex_between flex_vcenter">
              <span class="label">
                用法
                <i class="point"></i>
              </span>
              <selector2
                :options="TAKE_WAY"
                wrapClass="text-right"
                @selectchange="handleTakeWayChange"
                label="wayName"
                :defaultValue="item.takeWay"
              ></selector2>
            </li>
            <!-- <li class="flex flex_between flex_vcenter">
              <span class="label">用法</span>
              <input type="text" maxlength="5" placeholder="选填，如口服" v-model="useMethod" />
            </li>-->
            <li class="flex flex_between flex_vcenter">
              <span class="label">用量</span>
              <input type="text" maxlength="5" placeholder="选填（如1片）" v-model="item.dosage" />
            </li>
          </ul>
          <div>
            <ul class="topList">
              <li class="flex flex_between flex_vcenter">
                <span class="label">
                  提醒日期
                  <i class="point"></i>
                </span>
                <!-- <mu-date-picker hintText="选择用药日期" v-model="drugDate" :minDate="new Date()" /> -->
                <div>
                  <span class="pr10" @click="showDatePicker('start')">{{item.beginTime  || '请选择开始日期'}}</span>至
                  <span class="pl10" @click="showDatePicker('end')">{{item.endTime || '请选择结束日期'}}</span>
                </div>
              </li>
              <li class="flex flex_between flex_vcenter">
                <span class="label">
                  提醒频次
                  <i class="point"></i>
                </span>
                <selector2
                  :options="UES_RATE"
                  wrapClass="text-right"
                  @selectchange="handleRateChange"
                  label="rateName"
                  :defaultValue="item.methodName"
                ></selector2>
              </li>
              <li class="flex flex_between flex_vcenter" v-if="item.remindDayList && item.remindDayList.length > 0">
                <span class="label">
                  周期日
                  <i class="point"></i>
                </span>
              </li>
              <ul class="remindTimesList" v-if="item.remindDayList && item.remindDayList.length > 0">
                <li 
                  class="flex flex_between flex_vcenter"
                  v-for="(value, index) in item.remindDayList"
                  :key="index"
                >
                  <span>第{{index + 1}}次提醒周期日</span>
                  <div class="flex flex_vcenter">
                    <selector2
                      :options="item.rateDayArr"
                      wrapClass="text-right"
                      @selectchange="handleWeekChange(index, $event)"
                      label="label"
                      :defaultValue="value | filterDay"
                    ></selector2>
                  </div>
                </li>
              </ul>
              <li class="flex flex_between flex_vcenter" v-if="item.remindTimesList && item.remindTimesList.length > 0">
                <span class="label">
                  提醒次数
                  <i class="point"></i>
                </span>
              </li>
              <ul class="remindTimesList" v-if="item.remindTimesList && item.remindTimesList.length > 0">
                <li
                  class="flex flex_between flex_vcenter"
                  style="padding-right: 15px;"
                  v-for="(value, index) in item.remindTimesList"
                  :key="index"
                >
                  <span>第{{index + 1}}次提醒时间</span>
                  <div class="flex flex_vcenter flex_right" style="min-width: 100px;" @click="selectTime(index)">
                    <span v-if="value && value.hour && value.min">{{value.hour}}:{{value.min}}</span>
                    <span v-else class="pl10"></span>
                    <i class="iconfont icon-small-arrow-right"/>
                  </div>
                </li>
              </ul>
            </ul>
          </div>
          <ul class="topList">
            <li class="flex flex_between flex_vcenter">
              <span class="label">
                消息推送
                <i class="point"></i>
              </span>
              <div>
                <mu-switch v-model="item.pushFlag" />
              </div>
            </li>
          </ul>
        </div>
      </swipe-item>
    </swipe>
    <div class="opera-btn">
      <div v-show="list.length < 2 || currentIndex == list.length -1"><mu-raised-button class="btn" label="保存" fullWidth primary @click="submitAdd()" /></div>

      <div class="flex" v-show="currentIndex > 0 && currentIndex < list.length -1">
        <mu-raised-button class="btn" label="上一页" style="width:50%;" primary @click="pre()" />
        <mu-raised-button class="btn" label="下一页" style="width:50%;" primary @click="next()" />
      </div>
      <div v-show="list.length >= 2 && currentIndex == 0">
        <mu-raised-button class="btn" :label="`下一页 (${currentIndex + 1}/${list.length})`" fullWidth primary @click="next()" />
      </div>
    </div>
    <mu-dialog :open="timePickerDialog" @close="closetimePicker">
      <timePicker
        :address="defaltTime"
        @closeDialog="closetimePicker"
        @confirmSelectTime="confirmSelectTime"
      ></timePicker>
    </mu-dialog>
  </div>
</template>

<script>
import Selector2 from "../../components/Selector2";
import "vue-swipe/dist/vue-swipe.css";
import { Swipe, SwipeItem } from "vue-swipe";
import timePicker from "../../components/BsTimePicker.vue";
import { commonAjaxJson, RESTFUL_API } from "../../api/api";
const WEEKS = [
        { label: "星期一", value: "2" },{ label: "星期二", value: "3" },
        { label: "星期三", value: "4" },{ label: "星期四", value: "5" },
        { label: "星期五", value: "6" },{ label: "星期六", value: "7" },
        { label: "星期天", value: "1" }
      ]
export default {
  components: { Selector2, Swipe, SwipeItem, timePicker },
  data() {
    return {
      hospitalCode: sessionStorage.getItem("hospitalCode") || "",
      familyPerson: JSON.parse(sessionStorage.getItem("familyPerson")) || {},
      currentIndex: 0,
      rateDayArr: [],
      TAKE_WAY: [],
      UES_RATE: [],
      timePickerDialog: false,
      currentTimeIndex: "",
      defaltTime: ["12","00"],
    };
  },
  props: {
    list: {
      type: Array
    }
  },
  filters: {
    filterDay (val){
      return `第${val}日`
    }
  },
  mounted (){
    this.getUseRate()
    this.getTakeWay()
    this.currentIndex = this.$refs.swipe.index
  },
  methods: {
    getUseRate() {
      commonAjaxJson(RESTFUL_API.getUseRate, {hospitalCode: this.hospitalCode}, true).then(res => {
        if(res.data.code == 200) {
          res.data.data.map(v => {
            if(v.rateDay > 1) {
              let rateDayArr = []
              for(let j = 1; j <= v.rateDay; j++) {
                rateDayArr.push({label: `第${j}日`, value: String(j)})
              }
              v.rateCycleArr = v.rateCycle.split(",")
              v.rateDayArr = rateDayArr
            }
          })
          this.UES_RATE = res.data.data
        }
      })
    },
    getTakeWay() {
      commonAjaxJson(RESTFUL_API.getTakeWay, {hospitalCode: this.hospitalCode}, true).then(res => {
        if(res.data.code == 200) {
          this.TAKE_WAY = res.data.data
        }
      })
    },
    handleTakeWayChange (v){
      let currentIndex = this.currentIndex
      this.list[currentIndex].takeWay = v.wayName
      this.list[currentIndex].useMethod = v.useMethod
    },
    handleRateChange (v){
      let currentIndex = this.currentIndex
      this.list[currentIndex].rateDayArr = v.rateDayArr
      this.list[currentIndex].remindTimesList = [];
      this.list[currentIndex].times = v.rateTimes;
      this.list[currentIndex].rateDay = v.rateDay;
      this.list[currentIndex].methodName = v.rateName;
      this.list[currentIndex].rateName = v.rateName;
      this.list[currentIndex].remindDayList = v.rateCycleArr || [];
      v.rateHisTime.split(",").forEach((val, index) => {
       this.list[currentIndex].remindTimesList.push({hour: val.split(":")[0], min: val.split(":")[1]})
      })
    },
    handleWeekChange (index, v){
      let currentIndex = this.currentIndex
      this.list[currentIndex].remindDayList[index] = v.value
    },
    selectTime(index) {
      // 修改某一条提醒时间
      this.currentTimeIndex = index;
      this.timePickerDialog = true;
      let currentIndex = this.currentIndex;
      let curItem = this.list[currentIndex]
      let cur = curItem.remindTimesList[this.currentTimeIndex];
      let d = new Date();
      let hour = d.getHours();
      let min = d.getMinutes();
      if (!cur.hour && cur.hour != "00") {
        cur.hour = hour < 10 ? "0" + hour : "" + hour;
        cur.min = min < 10 ? "0" + min : "" + min;
      }
      this.defaltTime = [cur.hour, cur.min];
    },
    confirmSelectTime(time) {
      let currentIndex = this.currentIndex;
      let curItem = this.list[currentIndex]
      curItem.remindTimesList[this.currentTimeIndex].hour = time[0];
      curItem.remindTimesList[this.currentTimeIndex].min = time[1];
      this.timePickerDialog = false;
    },
    closetimePicker() {
      this.timePickerDialog = false;
    },
    showDatePicker(type) {
      let currentIndex = this.currentIndex
      let curItem = this.list[currentIndex]
      this.$picker.show({
        date:
          type === "start"
            ? curItem.beginTime
            : type === "end"
            ? curItem.endTime
            : "",
        succeed: e => {
          if (type === "start") {
            let beginTime = e;
            if (
              !!curItem.endTime &&
              new Date(beginTime).getTime() >
                new Date(curItem.endTime).getTime()
            ) {
              this.$store.commit("UPDATE_TOAST", {
                message: "开始时间须小于结束时间"
              });
              return;
            }
            curItem.beginTime = e;
          } else if (type === "end") {
            let endTime = e;
            if (
              !!curItem.beginTime &&
              new Date(curItem.beginTime).getTime() >
                new Date(endTime).getTime()
            ) {
              this.$store.commit("UPDATE_TOAST", {
                message: "开始时间须小于结束时间"
              });
              return;
            }
            curItem.endTime = e;
          }
        }
      });
    },
    swipeChange (val){
      this.currentIndex = val
    },
    pre (){
      this.$refs.swipe.pre()
      // if(this.currentIndex > 1) {
      //   this.currentIndex = this.$refs.swipe.index - 1
      // }
    },
    next (){
      // console.log(this.$refs.swipe)
      this.$refs.swipe.next()
      // if(this.currentIndex < this.list.length) {
      //   this.currentIndex = this.$refs.swipe.index + 1
      // }
    },
    submitAdd (){
      let params = {
        fid: this.familyPerson.id,
        uid: this.familyPerson.uid,
        reminderList: this.list
      }
      
      let reminderList = this.list.map((val, index) => {
        let timesArray = []
        if(val.rateDay > 1){
          for (let i = 0; i < val.remindTimesList.length; i++) {
            if ( val.remindTimesList[i].hour != "" && val.remindTimesList[i].min != "" ) {
              timesArray.push(
                val.remindDayList[i] + "#" + val.remindTimesList[i].hour + ":" + val.remindTimesList[i].min
              );
              val.reminderTime = timesArray.join(",")
            }
          }
        } else {
          for (let i = 0; i < val.remindTimesList.length; i++) {
            if ( val.remindTimesList[i].hour != "" && val.remindTimesList[i].min != "" ) {
              timesArray.push(
                val.remindTimesList[i].hour + ":" + val.remindTimesList[i].min
              );
            }
          }
          val.reminderTime = timesArray.join(",")
        }
        return {
          drugId: "",
          drugName: val.drugName,
          takeWay: val.takeWay,
          startTime: val.beginTime,
          endTime: val.endTime,
          useMethod: val.useMethod,
          rateName: val.rateName,
          cycle: val.rateDay,
          dosage: val.dosage,
          times: val.times,
          reminderTime: val.reminderTime,
          pushFlag: val.pushFlag ? 0 : 1
        }
      })
      params.reminderList = reminderList
      commonAjaxJson(RESTFUL_API.exportReminder, params, true).then(res => {
        if (res.data.code == 200) {
          this.$store.commit("UPDATE_TOAST", {
            message: "保存成功",
            fn: () => {
              // this.$router.push({
              //   path: "/drugReminder/index"
              // });
              this.$router.go(-1)
            }
          });
        } else {
          this.$store.commit("UPDATE_TOAST", {
            message: res.data.message
          });
        }
      })
    }
  }
};
</script>

<style lang="less" scoped>
@import "../../common/css/component";
.maxlen {
  white-space: nowrap;
}
.topList {
  background-color: white;
  margin-top: 10px;
  > li {
    margin-left: 10px;
    border-bottom: 1px solid @color-border;
    padding: 10px;
  }
  input {
    border: none;
    outline: none;
    width: 180px;
    text-align: right;
    // &[name="drugName"]{
    //   width: 270px;
    // }
  }
}
.point {
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background-color: red;
  margin-bottom: 4px;
}
.doubleBtn {
  width: 120px;
  border: 1px solid @color-primary;
  color: @color-primary;
  border-radius: 5px;
  > div {
    width: 60px;
    text-align: center;
    padding: 4px 0;
  }
  .activeOne {
    background-color: @color-primary;
    color: white;
  }
}
.everyDayBox {
  background-color: white;
  > div {
    margin-left: 10px;
    border-bottom: 1px solid @color-border;
    padding: 10px;
  }
  .addIcon {
    width: 20px;
    vertical-align: bottom;
  }
}
.addIcon {
  width: 20px;
  vertical-align: bottom;
}
.remindTimesList {
  > li {
    margin-left: 24px;
    border-bottom: 1px solid @color-border;
    padding: 10px;
    img {
      height: 16px;
      margin-left: 5px;
    }
  }
}
.onlyOneBox {
  > ul {
    margin-top: 0;
  }
}
.centerT {
  padding: 0 5px;
}
.opera-btn {
  position: absolute;
  bottom: 0;
  width: 100%;
  z-index: 9;
  .btn {
    height: 44px;
    line-height: 44px;
    font-size: 16px;
  }
}
</style>